package com.smedi.ismedi.progress.core.port.adapter.persistence.repository.impl;

import com.smedi.ismedi.constructionproject.api.dto.response.resp.ProjectResp;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.Project;
import com.smedi.ismedi.progress.core.domain.dto.ProjectQuery;
import com.smedi.ismedi.progress.core.domain.repository.ProjectRepository;
import com.smedi.ismedi.progress.core.port.adapter.convert.AdapterConverter;
import com.smedi.ismedi.progress.core.port.adapter.service.ProjectRemoteService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author Jimmy
 * @Date 2021/6/1 13:45
 */
@Service
@AllArgsConstructor
public class ProjectRepositoryImpl implements ProjectRepository {
    private final AdapterConverter adapterConverter;

    private final ProjectRemoteService projectRemoteService;


    @Override
    public Project getProjectOne(ProjectQuery projectQuery) {
        ProjectResp projectResp = projectRemoteService.getProjectOne(projectQuery);

        return this.extend(projectResp);
    }

    @Override
    public List<Project> getProjectList(ProjectQuery projectQuery) {
        List<ProjectResp> projectResps = projectRemoteService.getProjectList(projectQuery);

        return this.extend(projectResps);
    }

    private Project extend(ProjectResp projectResp) {
        if (null == projectResp) {
            return null;
        }

        List<ProjectResp> projectResps = new ArrayList<>();
        projectResps.add(projectResp);
        List<Project> projects = this.extend(projectResps);

        return projects.get(0);
    }

    private List<Project> extend(List<ProjectResp> projectResps) {
        if (projectResps.isEmpty()) {
            return new ArrayList<>();
        }
        List<Project> projects = new ArrayList<>();

        for (ProjectResp projectResp : projectResps) {
            Project project = adapterConverter.projectRespToProject(projectResp);

            projects.add(project);
        }

        return projects;
    }
}
